package cn.ac.iie.di.wx.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Hex;

public class IDSHAGeneratorImpl {

    public static String getId(String _ch, String _spec, String asp, String adp, String _key)
            throws Exception {
        if ((_ch == null) || (_ch.isEmpty()) || (_spec == null) || (_spec.isEmpty()) || (_key == null)
                || (_key
                .isEmpty())) {
            throw new Exception("_ch _spec _key 不能为空");
        }

        if (((asp == null) || (asp.isEmpty())) && ((adp == null) || (adp.isEmpty()))) {
            throw new Exception("asp 与 adp 不能同时为空");
        }

        if (asp == null) {
            asp = "";
        }
        if (adp == null) {
            adp = "";
        }

        StringBuffer _id = new StringBuffer();
        _id = _id.append(_ch);
        _id = _id.append(_spec);
        _id = _id.append("_");

        if (!asp.isEmpty()) {
            if (asp.equals(adp)) {
                _id = _id.append(asp);
            } else {
                _id = _id.append(asp).append("_").append(adp);
            }
        } else {
            _id = _id.append(asp).append("_").append(adp);
        }

        _id = _id.append("_");
        if (_key.length() < 64) {
            _id = _id.append(_key);
        } else {
            String sha = SHA256(_key);
            if (sha != null) {
                _id = _id.append(sha);
            } else {
                return null;
            }
        }

        return _id.toString();
    }

    public static String SHA256(String source) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(source.getBytes("UTF-8"));
        return Hex.encodeHexString(hash);
    }

//    public static void main(String[] args) throws Exception {
//        String _id = getId("40", "U-WX03-A", "WeChat", "WeChat", "5fdc0bf9636bbc4d67ef53e7f050eb77baaea780");
//        System.out.println(_id);
//        String str = "{\"cmd\":4,\"wxid\":\"" + "5fdc0bf9636bbc4d67ef53e7f050eb77baaea780" + "\"}";
//        JSONObject requestObject = JSONObject.parseObject(str);
//        String wxid = requestObject.getString("wxid");
//        System.out.println(wxid);
//    }
}
